// 生成唯一的 user_id，逻辑同 resource_id
const MAX_LENGTH = 50;
function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}

async function generateUniqueUserId() {
    let userId;
    let isUnique = false;
    while (!isUnique) {
        userId = generateRandomString(50);
        const checkResponse = await fetch(`/check-user-id?userId=${userId}`);
        const checkData = await checkResponse.json();
        if (!checkData.exists) {
            isUnique = true;
        }
    }
    return userId;
}

// 验证输入信息并打开确认模态框
async function validateAndOpenConfirmModal() {
    const username = document.getElementById('regUsername').value;
    const email = document.getElementById('regEmail').value;
    const password = document.getElementById('regPassword').value;
    const confirmPassword = document.getElementById('regConfirmPassword').value;
    const name = document.getElementById('regName').value;
    const studentId = document.getElementById('regStudentId').value;
    const role = document.getElementById('regRole').value;

    if(username.length>MAX_LENGTH||email.length>MAX_LENGTH||name.length>MAX_LENGTH||studentId.length>MAX_LENGTH){
        alert('输入信息过长,不能超过50个字符，请重新输入');
        return;
    }
    const usernameRegex = /^[a-zA-Z0-9]{3,10}$/;
    const passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{10,}$/;

    const usernameData = await fetch(`/check-username?username=${username}`);
    const usernameExists = await usernameData.json();

    const studentIdData = await fetch(`/check-student-id?studentId=${studentId}`);
    const studentIdExists = await studentIdData.json();

    if (!usernameRegex.test(username)) {
        document.getElementById('regUsername').placeholder = '用户名不符合条件（字母和数字，3 - 10 位）';
        alert('用户名不符合条件');
        return;
    }

    if(!email.includes('@') || !email.includes('.')) {
        alert('邮箱格式不正确');
        return;
    }
    if(!name){
        alert('姓名不能为空');
        return;
    }

    if(!studentId){
        alert('学号不能为空');
        return;
    }

    if (studentIdExists.exists) {
        alert('学号已被使用');
        return;
    }

    if (!passwordRegex.test(password)) {
        document.getElementById('regPassword').placeholder = '密码不符合条件（包含数字、大写字母和小写字母，不少于 10 位）';
        alert('密码不符合条件');
        return;
    }

    if (password!== confirmPassword) {
        alert('确认密码与密码不一致');
        return;
    }

    if (usernameExists.exists) {
        alert('用户名已存在');
        return;
    }

    await openConfirmModal();
}

// 打开确认模态框
async function openConfirmModal() {
    const username = document.getElementById('regUsername').value;
    const email = document.getElementById('regEmail').value;
    const password = document.getElementById('regPassword').value;
    const confirmPassword = document.getElementById('regConfirmPassword').value;
    const name = document.getElementById('regName').value;
    const studentId = document.getElementById('regStudentId').value;
    const role = document.getElementById('regRole').value;

    const userId = await generateUniqueUserId();

    document.getElementById('confirmUsername').textContent = username;
    document.getElementById('confirmRole').textContent = role;
    document.getElementById('confirmStudentId').textContent = studentId;
    document.getElementById('confirmStudentEmail').textContent = email;
    const modal = document.getElementById('confirmModal');
    
    // 显示模态框并启用交互
    modal.classList.remove('opacity-0', 'pointer-events-none');
    modal.querySelector('.modal-content').classList.remove('scale-95');
    modal.querySelector('.modal-content').classList.add('scale-100');
    // 存储用户信息和生成的 user_id
    window.userRegistrationData = {
        userId,
        username,
        email,
        password,
        name,
        student_id: studentId,
        role
    };
}

// 关闭确认模态框
function closeConfirmModal() {
    const modal = document.getElementById('confirmModal');
    modal.classList.add('opacity-0', 'pointer-events-none');
    modal.querySelector('.modal-content').classList.remove('scale-100');
    modal.querySelector('.modal-content').classList.add('scale-95');
}

// 确认注册
async function confirmRegister() {
    const { userId, username, email, password, name, student_id, role } = window.userRegistrationData;

    const response = await fetch('/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ userId, username, email, password, name, student_id, role })
    });
    const data = await response.json();
    alert(data.message);
    closeConfirmModal();
    window.location.href = 'login.html';
}

export{
    generateRandomString,
    generateUniqueUserId,
    validateAndOpenConfirmModal,
    openConfirmModal,
    closeConfirmModal,
    confirmRegister,
}